﻿Option Strict On
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Imports Kudos2Mod.Common

Module CSV

    Public Function GetDataSet(ByVal filename As String, ByVal columnsExpected As Integer) As DataSet
        Dim connString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Text;", Path.GetDirectoryName(filename))
        Dim cmdString As String = String.Format("SELECT * FROM {0}", Path.GetFileName(filename))
        Dim dataset As New DataSet
        Dim conn As New OleDbConnection(connString)

        conn.Open()
        Dim adapter As New OleDbDataAdapter
        adapter.SelectCommand = New OleDbCommand(cmdString, conn)
        adapter.Fill(dataset, "data")
        conn.Close()

        If dataset.Tables("data").Columns.Count <> columnsExpected Then
            RewriteFirstLineOfCSV(filename, dataset.Tables("data").Columns.Count, 21)
            dataset.Tables("data").Clear()
            conn.Open()
            adapter = New OleDbDataAdapter
            adapter.SelectCommand = New OleDbCommand(cmdString, conn)
            adapter.Fill(dataset, "data")
            conn.Close()
        End If

        Return dataset
    End Function

    Private Sub RewriteFirstLineOfCSV(ByVal filename As String, ByVal currentColumns As Integer, ByVal columnsExpected As Integer)
        Try
            Dim line As String
            Dim readFile As System.IO.TextReader = New StreamReader(filename)
            Dim writeFile As System.IO.TextWriter = New StreamWriter(FilesPath & "\temp.csv")
            Dim bFirstLine As Boolean = True
            While True
                line = readFile.ReadLine()
                If line Is Nothing Then
                    Exit While
                Else
                    If bFirstLine Then
                        If currentColumns < columnsExpected Then
                            line = AddCommasToEnd(line, currentColumns, columnsExpected)
                        End If
                        bFirstLine = False
                    End If
                    writeFile.WriteLine(line)
                End If
            End While
            readFile.Close()
            readFile = Nothing
            writeFile.Flush()
            writeFile.Close()
            writeFile = Nothing
            'File.Delete(filename)
            My.Computer.FileSystem.MoveFile(FilesPath & "\temp.csv", filename, True)
        Catch ex As IOException
            MsgBox(ex.ToString)
        End Try

    End Sub

    Private Function AddCommasToEnd(ByVal line As String, ByVal curCommas As Integer, ByVal endCommas As Integer) As String
        Dim i As Integer
        For i = curCommas To endCommas
            line &= ","
        Next
        AddCommasToEnd = line
    End Function

End Module
